import actors.remote.Node
import actors.remote.Node._
import actors.remote.RemoteActor._
import actors.{AbstractActor, Actor}
import java.util.{Timer, TimerTask}

/**
 * Created by Yair, using IntelliJ IDEA.
 * Date: 13/06/11
 * Time: 11:27
 */



//////////////////////////////////////////////////
//      what if disconnected from the server???
////////////////////////////////////////////////


object observer_server{
  //the server's preferences - get config from manager
  private var serverIP: String = "localhost"
  private var serverPORT: Int = 9992
  private var userName: String = null
  private var key = -1

  private var server: AbstractActor = null
  private val downloadsManager = Downloads
  private val timer = new Timer


  def initServer(): Unit = { server = select(Node(serverIP, serverPORT), 'cdb_server)  }       //select??

  def setObserverServer(serverIP: String, serverPORT: Int, useName: String, key: Int): Unit = {
    this.serverIP = serverIP
    this.serverPORT = serverPORT
    this.userName = useName
    this.key = key
  }

  private val work = true

  //the operation to perform
  private class ping extends TimerTask{
    override def run(){

      val d_work = (Downloads ! isWorking).asInstanceOf[Boolean]
      val u_work = (Uploads ! isWorking).asInstanceOf[Boolean]

      if (d_work == false && u_work == false){
        val update = new newUpdate(userName, key)

        if (Manager.isConnected){
          val result = (server !? update).asInstanceOf[newUpdate]

          //if got files to download - send their list to the downloads manager
          if (result.file != null){
            if (Manager.isConnected){
                if (result.deleteFile == false)
                  downloadsManager ! result.file

                  //else  - remove the file
                 else{
                  Manager.deleteFile(result.file)
                }
            }
          }
        }
      }
      //else - skip one ping
    }
  }


  //start the pinging to the server every 0.25 seconds
def startPinging(): Unit = {
  //start executing pings every 0.25 seconds
  timer.scheduleAtFixedRate(new ping,0, 250)
}

  //stop the pinging routine
  def stopPinging(): Unit = {
    timer.cancel
  }

}